package com.ryskoo.catering.coupondetail.service;

import com.ryskoo.catering.coupon.domain.CouponPO;
import com.ryskoo.catering.coupondetail.domain.CouponDetailPO;
import com.ryskoo.catering.coupondetail.repository.ICouponDetailRepository;
import com.ryskoo.catering.productmain.domain.ProductMainPO;
import com.ryskoo.catering.productmain.service.IProductMainService;
import com.ryskoo.common.hclconstant.CouponStateEnum;
import com.ryskoo.customer.customer.domain.CustomerPO;
import com.ryskoo.customer.customer.service.ICustomerService;
import com.ryskoo.framework.core.bean.QueryConditionEnum;
import com.ryskoo.framework.core.bean.QueryMessageDTO;
import com.ryskoo.framework.core.exception.InvalidParamException;
import com.ryskoo.framework.core.generator.SnowflakeIdWorker;
import com.ryskoo.framework.core.service.BasicServiceImpl;
import com.ryskoo.framework.core.utils.DateFormatHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CouponDetailServiceImpl extends BasicServiceImpl<CouponDetailPO> implements ICouponDetailService {
    @Autowired
    private ICouponDetailRepository couponDetailRepository;
    
    @Autowired
    private IProductMainService productMainService;
    
    @Autowired
    private ICustomerService customerService;
    

    @PostConstruct
    public void init() {
        this.setDao(couponDetailRepository);
    }

    @Override
    public List<CouponDetailPO> getListByCustomerUuidAndCouponUuids(String customerUuid, List<String> couponUuids) {
        return couponDetailRepository.getListByCustomerUuidAndCouponUuids(customerUuid, couponUuids);
    }

    @Override
    public List<CouponDetailPO> getListByCustomerUuidAndCouponUuid(String customerUuid, String couponUuid) {
        return couponDetailRepository.getListByCustomerUuidAndCouponUuid(customerUuid, couponUuid);
    }

    /**
     * 领取优惠券
     * @param coupon
     * @param customerUuid
     */
    @Override
    public void receive(CouponPO coupon, String customerUuid) {
    	// 获得会员名称
    	CustomerPO customer = customerService.getByUuid(customerUuid);
    	if(customer == null){
    		throw new InvalidParamException("当前会员不存在！");
    	}
        CouponDetailPO detail = new CouponDetailPO();
        detail.setVendorUuid(coupon.getVendorUuid());
        detail.setCustomerUuid(customerUuid);
        detail.setCustomerName(customer.getLoginName());
        detail.setCouponUuid(coupon.getUuid());
        detail.setCouponNo(new SnowflakeIdWorker().nextId() + "");
        detail.setCouponName(coupon.getCouponName());
        detail.setCouponType(coupon.getCouponType());
        detail.setCouponPrice(coupon.getCouponPrice());
        detail.setReachPrice(coupon.getReachPrice());
        detail.setState(CouponStateEnum.UNUSED.getValue());
        detail.setStartValidTime(coupon.getStartValidTime());
        detail.setEndValidTime(coupon.getEndValidTime());
        detail.setReceiveTime(DateFormatHelper.getNowTimeStr());
        detail.setProductUuid(coupon.getProductUuid());
        this.create(detail);
    }

    /**
     * 获取最优的单品优惠券
     * @param customerUuid
     * @param productUuid
     * @param price
     * @return
     */
    @Override
    public CouponDetailPO getBestCouponDetail(String customerUuid, String productUuid, double price) {
        List<CouponDetailPO> list = this.getCouponDetailList(customerUuid, productUuid, price);
        if(CollectionUtils.isNotEmpty(list)){
            Collections.sort(list, new Comparator<CouponDetailPO>() {
                @Override
                public int compare(CouponDetailPO o1, CouponDetailPO o2) {
                    if(o1.getEndValidTime().compareTo(o2.getEndValidTime()) < 0){
                        return -1;
                    }else if(o1.getEndValidTime().compareTo(o2.getEndValidTime()) > 0){
                        return 1;
                    }else{
                        if(o1.getCouponPrice() - o2.getCouponPrice() > 0){
                            return -1;
                        }else if(o1.getCouponPrice() - o2.getCouponPrice() < 0){
                            return 1;
                        }else{
                            return 0;
                        }
                    }
                }
            });
            return list.get(0);
        }else{
            return null;
        }

    }

    /**
     * 获取会员可用单品优惠券
     * @param customerUuid
     * @param productUuid
     * @param price
     * @return
     */
    @Override
    public List<CouponDetailPO> getCouponDetailList(String customerUuid, String productUuid, double price) {
        return couponDetailRepository.getCouponDetailList(customerUuid, productUuid, price);
    }

    /**
     * 获取会员可用的店铺优惠券
     * @param customerUuid
     * @param vendorUuid
     * @param price
     * @return
     */
    @Override
    public List<CouponDetailPO> getVendorCouponDetailList(String customerUuid, String vendorUuid, double price) {
        return couponDetailRepository.getVendorCouponDetailList(customerUuid, vendorUuid, price);
    }

    /**
     * 使用优惠券
     * @param couponDetailUuid
     * @param orderId
     */
    @Override
    public void used(String couponDetailUuid, String orderId) {
        this.used(couponDetailUuid, orderId, DateFormatHelper.getNowTimeStr());
    }

    /**
     *批量使用优惠券
     * @param couponDetailUuids
     * @param orderId
     */
    @Override
    public void used(List<String> couponDetailUuids, String orderId) {
        String nowTime = DateFormatHelper.getNowTimeStr();
        for(String uuid : couponDetailUuids){
                this.used(uuid, orderId, nowTime);
        }
    }

    private void used(String couponDetailUuid, String orderId, String useTime){
        CouponDetailPO couponDetail = this.getByUuid(couponDetailUuid);
        couponDetail.setState(CouponStateEnum.USED.getValue());
        couponDetail.setUseTime(useTime);
        couponDetail.setOrderId(orderId);
        this.update(couponDetail);
    }
    
    @Override
	public List<CouponDetailPO> queryListAndProductByCondition(QueryMessageDTO qm) {
		List<CouponDetailPO> list = this.queryByConditionAndPage(qm);
		if(CollectionUtils.isNotEmpty(list)){
			List<String> productUuids = list.stream().filter(CouponDetailPO->StringUtils.isNotEmpty(CouponDetailPO.getProductUuid())).map(CouponDetailPO::getProductUuid).collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(productUuids)){
				// 根据productUuids获取ProductMain
				QueryMessageDTO productQm = new QueryMessageDTO();
				productQm.addCondition("uuid", QueryConditionEnum.IN.name(), productUuids);
				List<ProductMainPO> productList = productMainService.getProductInfoFromES(productQm);
				if(CollectionUtils.isNotEmpty(productList)){
					// 设置map
					Map<String,String> productMap = new HashMap<String,String>();
					productList.stream().forEach(ProductMainPO -> productMap.put(ProductMainPO.getUuid(), ProductMainPO.getName()));
					list.stream().forEach(CouponDetailPO -> CouponDetailPO.setProductName(productMap.get(CouponDetailPO.getProductUuid())));
				}
			}
		}
		return list;
	}
    
}
